package com.ruoyi.lm.service.impl;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.menu.AccessToken;
import com.ruoyi.common.utils.menu.TemplateData;
import com.ruoyi.common.utils.menu.WeiXinUtil;
import com.ruoyi.common.utils.menu.WxTemplate;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import java.util.HashMap;
import java.util.Map;


public class WxTemplateMsgService {
    Logger log = LoggerFactory.getLogger(getClass());





    /**
     * 发送模板消息
     */
    public String send_template_message(String openId, String appId, String appSecret, String text) throws Exception {
        AccessToken token = WeiXinUtil.getAccessToken(appId, appSecret);
        String access_token = token.getAccessToken();
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+access_token;
        WxTemplate temp = new WxTemplate();
//        temp.setUrl("http://weixin.qq.com/download");
        temp.setTouser(openId);
        temp.setTopcolor("#000000");
        temp.setTemplate_id("rglC2IqnPQ9NJ2vyU-NICtH2BUxJFLOM2T7vgFB4osk");//TODO 模板消息id
        Map<String, TemplateData> m = new HashMap<String, TemplateData>();
        TemplateData first = new TemplateData();
        first.setValue("尊敬的用户,您好\n" +
                "\n" +
                "你发布的"+text+"有人报名，请及时查看");
        first.setColor("#000000");
        m.put("first", first);
        TemplateData keyword1 = new TemplateData();
        keyword1.setValue(DateUtils.getDate());
        keyword1.setColor("#000000");
        m.put("keyword1", keyword1);
        TemplateData keyword2 = new TemplateData();
        keyword2.setValue(text + "报名");
        keyword2.setColor("#000000");
        m.put("keyword2", keyword2);
        TemplateData remark = new TemplateData();
        remark.setValue("感谢您对我们的信任！");
        remark.setColor("#000000");
        m.put("remark", remark);
        temp.setData(m);
        String jsonString = JSONObject.fromObject(temp).toString();
        System.out.println("jsonstring"+jsonString);
        JSONObject jsonObject = WeiXinUtil.httpRequest(url, "POST", jsonString);
        System.out.println(jsonObject);
        int result = 0;
        if (null != jsonObject) {
            if (0 != jsonObject.getInt("errcode")) {
                result = jsonObject.getInt("errcode");
                log.error("错误 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
            }
        }
        log.info("模板消息发送结果："+result);
        return "qiangdan";
    }


}
